/**
 * 
 */
package org.lex.ftp.net.find;

import java.io.IOException;

import org.lex.filter.Filter;
import org.lex.filter.Filters;
import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.IFTPFile;

public class FTPFileFinder extends FTPFileIterator implements Runnable {
	private boolean stop = false;
	private final FinderObserver observer;
	private IFTPClient ftp = null;
	private Filter<IFTPFile> filter = Filters.acceptAllFilter();

	public FTPFileFinder(FinderObserver observer, IFTPClient ftp, String initPath, Filter<IFTPFile> filter) {
		super(ftp, initPath);
		this.observer = observer;
		this.ftp = ftp;
		this.filter = filter;
	}

	public void stop() {
		this.stop = true;
	}

	public void start() {
		this.stop = false;
		this.run();
	}

	public void run() {
		this.backup();
		while (false == stop && this.hasNext()) {
			IFTPFile file = this.next();
			if (this.filter.accept(file))
				this.observer.process(file);
		}
		// done
		this.restore();
		observer.done();
	}

	private String pwd = null;

	private void backup() {
		try {
			this.pwd = ftp.pwd();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void restore() {
		if (null != pwd)
			try {
				ftp.cwd(pwd);
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
}
